import { NavBar, InfiniteScroll, Popup, Toast } from 'antd-mobile'
import { useHistory, useParams } from 'react-router-dom'
import classNames from 'classnames'
import styles from './index.module.scss'

import Icon from '@/components/Icon'
import CommentItem from './components/CommentItem'
import CommentFooter from './components/CommentFooter'
import { useEffect, useRef, useState } from 'react'

import {
  addComment,
  fav,
  follow,
  getArticleDetail,
  getComments,
  like,
  likeComment,
  unFav,
  unFollow,
  unLike,
  unLikeComment,
} from '@/api/article'
import { ArticleCommentItem, ArticleDetail } from '@/types/data'

import { formatTime } from '@/utils/utils'
import DOMPurify from 'dompurify'
// import { useCodeLight } from '@/hooks'
// import highlight from 'highlight.js'
import 'highlight.js/styles/dark.css'
import ContentLoader from 'react-content-loader'
import NoneComment from '@/components/NoneComment'
import CommentInput from './components/CommentInput'
import Reply from './components/Reply'

// 测试
const clean = DOMPurify.sanitize("<img src='x' onerror='alert(1)'>")
console.log(clean)
/**
 * 导航栏高度的常量
 */
const NAV_BAR_HEIGTH = 45
// 创建枚举，来表示评论类型
enum CommentType {
  Article = 'a',
  Comment = 'c',
}
type CommentReply = {
  visible: boolean
  commentItem: ArticleCommentItem
}

const Article = () => {
  const history = useHistory()
  const [loading, setLoading] = useState(true)
  // 1. 获取文章详情
  const params = useParams<{ artId: string }>()
  // console.log(params)
  const [detail, setDetail] = useState<ArticleDetail>({} as ArticleDetail)
  useEffect(() => {
    const getDetail = async () => {
      const { data } = await getArticleDetail(params.artId)
      console.log(data)
      setDetail(data)
      // 关闭loading
      setLoading(false)
    }
    getDetail()
    // 默认加载一次文章评论列表
    // const loadComments = async () => {
    //   const { data } = await getComments(
    //     CommentType.Article,
    //     params.artId,
    //     offset.current
    //   )
    //   console.log('pl:', data)
    //   let _list = []
    //   setCommentList((commentList) => {
    //     _list = [...commentList, ...data.results]
    //     return _list
    //   })
    //   if (_list.length === data.total_count) {
    //     setHasMore(false)
    //   } else {
    //     offset.current = data.last_id
    //   }
    // }
    // loadComments()
    // highlight.highlightElement(document.querySelector('#codes') as HTMLElement)
    const wrapper = wrapperRef.current
    // if (!wrapper) return
    const comment = commentRef.current
    if (!comment || !wrapper) return
    // 滚动位置
    const commentTop = comment.getBoundingClientRect().top
    console.log(
      '评论距离可视区高和内容滚动高度：',
      commentTop,
      wrapper.scrollTop
    )
  }, [params.artId])

  // document.querySelector('#codes') &&
  //   highlight.highlightElement(document.querySelector('#codes') as HTMLElement)

  // 2. 代码块高亮
  // useCodeLight()

  // 3. 点击评论滚动到指定位置
  const commentRef = useRef<HTMLDivElement>(null)
  const wrapperRef = useRef<HTMLDivElement>(null)
  const isShowComment = useRef(false)

  // 展示 or 隐藏评论内容
  const onShowComment = () => {
    const wrapper = wrapperRef.current
    // if (!wrapper) return
    const comment = commentRef.current
    if (!comment || !wrapper) return
    // 滚动位置
    const commentTop = comment.getBoundingClientRect().top
    console.log(
      '评论距离可视区高和内容滚动高度：',
      commentTop,
      wrapper.scrollTop
    )
    if (!isShowComment.current) {
      // 还没有展示评论信息，此时，就展示评论信息
      wrapper.scrollTo({
        // wrapper.scrollTop 表示已经滚动的距离
        top: commentTop - NAV_BAR_HEIGTH + wrapper.scrollTop,
        // 如果想要滚动时，带有动画效果，可以使用 smooth 即可
        behavior: 'smooth',
      })
      isShowComment.current = true
    } else {
      // 已经展示评论信息，此时，需要返回页面顶部
      wrapper.scrollTo({
        top: 0,
        behavior: 'smooth',
      })
      isShowComment.current = false
    }
  }

  // 4. 关注作者
  // const onFollow = async () => {
  //   if (!detail) return
  //   if (detail.is_followed) {
  //     await unFollow(detail.aut_id)
  //     setDetail({ ...detail, is_followed: false })
  //   } else {
  //     await follow(detail.aut_id)
  //     setDetail({ ...detail, is_followed: true })
  //   }
  // }

  // // 5. 收藏文章
  // const onCollected = async () => {
  //   if (!detail) return
  //   if (detail.is_collected) {
  //     await unFav(detail.art_id)
  //     setDetail({ ...detail, is_collected: false })
  //   } else {
  //     await fav(detail.art_id)
  //     setDetail({ ...detail, is_collected: true })
  //   }
  // }

  // 6. 统一处理关注作者、收藏文章、点赞文章
  /**
   *
   * @param type 类型
   * @param id 参数
   * @param sel 正向操作
   * @param unSel 反向操作
   * @returns
   */
  const onArticle = async (
    type: 'is_followed' | 'is_collected' | 'attitude',
    id: string,
    sel: Function,
    unSel: Function
  ) => {
    // if (!detail) return
    if (detail[type] && detail[type] !== -1) {
      await unSel(id)
      setDetail({ ...detail, [type]: type === 'attitude' ? 0 : false })
    } else {
      await sel(id)
      setDetail({ ...detail, [type]: type === 'attitude' ? 1 : true })
    }
  }

  // 7. 评论列表
  const [commentList, setCommentList] = useState<ArticleCommentItem[]>([])
  // 控制是否加载完成
  const [hasMore, setHasMore] = useState(true)
  // 分页偏移量offset
  const offset = useRef<string | null>(null)
  const loadMoreComments = async () => {
    const { data } = await getComments(
      CommentType.Article,
      params.artId,
      offset.current
    )
    console.log('pl:', data)
    setCommentList([...commentList, ...data.results])
    if (commentList.length === data.total_count) {
      setHasMore(false)
    } else {
      offset.current = data.last_id
    }
  }

  // 8. 添加评论
  const [commentVisible, setCommentVisible] = useState(false)

  const onCommentShow = () => setCommentVisible(true)
  const onCommentHide = () => setCommentVisible(false)
  // 对文章发表评论
  const onAddComment = async (content: string) => {
    // if (!detail) return
    const { data } = await addComment({ target: detail!.art_id, content })
    // 向文章评论列表追加最新评论数据
    // 注意：处理默认没有加载情况下，新增评论=》不进行本地新增
    commentList.length > 0 && setCommentList([data.new_obj, ...commentList])
    // 更新评论数量
    setDetail({ ...detail, comm_count: detail?.comm_count + 1 })
    // 关闭评论抽屉
    onCommentHide()
    Toast.show('评论成功')
  }

  // 9. 对文章评论点赞
  const onThumbsUp = async (com_id: string, is_liking: boolean) => {
    if (is_liking) {
      // 取消点赞
      await unLikeComment(com_id)
    } else {
      // 点赞
      await likeComment(com_id)
    }
    // 更新评论状态
    const newList = commentList.map((item) => {
      if (item.com_id === com_id) {
        return {
          ...item,
          is_liking: !is_liking,
          like_count: item.like_count + (is_liking ? -1 : 1),
        }
      }
      return item
    })
    setCommentList(newList)
  }

  // 10. 对评论回复
  const [commentReply, setCommentReply] = useState<CommentReply>({
    visible: false,
    commentItem: {} as ArticleCommentItem,
  })

  // 打开
  const onCommentReplyShow = (commentItem: ArticleCommentItem) => {
    setCommentReply({
      visible: true,
      commentItem,
    })
  }

  // 关闭
  const onCommentReplyHide = async (com_id: string, total: number) => {
    setCommentReply({
      ...commentReply,
      visible: false,
    })
    // 更新评论的回复数量
    const newList = commentList.map((item) => {
      if (item.com_id === com_id) {
        return {
          ...item,
          reply_count: total,
        }
      }
      return item
    })
    setCommentList(newList)
    // 更新总数
    const { data } = await getArticleDetail(params.artId)
    setDetail(data)
  }

  // 渲染文章及评论
  const renderArticle = () => {
    // 文章详情
    return (
      detail && (
        <div className="wrapper" ref={wrapperRef}>
          <div className="article-wrapper">
            <div className="header">
              <h1 className="title">{detail.title}</h1>

              <div className="info">
                <span>{formatTime(detail.pubdate)}</span>
                <span>{detail.read_count} 阅读</span>
                <span>{detail.comm_count} 评论</span>
              </div>

              <div className="author">
                <img src={detail.aut_photo} alt="" />
                <span className="name">{detail.aut_name}</span>
                <span
                  onClick={() =>
                    onArticle('is_followed', detail.aut_id, follow, unFollow)
                  }
                  className={classNames(
                    'follow',
                    detail.is_followed ? 'followed' : ''
                  )}>
                  {detail.is_followed ? '已关注' : '关注'}
                </span>
              </div>
            </div>

            <div className="content">
              <div
                className="content-html dg-html"
                dangerouslySetInnerHTML={{
                  __html: DOMPurify.sanitize(detail.content),
                }}
              />
              <div className="date">
                发布文章时间：{formatTime(detail.pubdate)}
              </div>
            </div>
          </div>

          <div className="comment" ref={commentRef}>
            <div className="comment-header">
              <span>全部评论（{detail.comm_count}）</span>
              <span>{detail.like_count} 点赞</span>
            </div>

            {detail.comm_count === 0 ? (
              <NoneComment />
            ) : (
              <div className="comment-list">
                {/* {Array.from(new Array(10)).map((item, i) => (
                <CommentItem key={i} />
              ))} */}
                {commentList.map((item) => (
                  <CommentItem
                    key={item.com_id}
                    {...item}
                    onThumbsUp={() => onThumbsUp(item.com_id, item.is_liking)}
                    onReply={() => onCommentReplyShow(item)}
                  />
                ))}

                <InfiniteScroll hasMore={hasMore} loadMore={loadMoreComments} />
              </div>
            )}
          </div>
        </div>
      )
    )
  }

  // 加载中，显示骨架屏
  if (loading) {
    return (
      // 根据当前页面结构，设计好的 loading 效果
      <ContentLoader
        speed={2}
        width={375}
        height={230}
        viewBox="0 0 375 230"
        backgroundColor="#f3f3f3"
        foregroundColor="#ecebeb">
        <rect x="16" y="8" rx="3" ry="3" width="340" height="10" />
        <rect x="16" y="26" rx="0" ry="0" width="70" height="6" />
        <rect x="96" y="26" rx="0" ry="0" width="50" height="6" />
        <rect x="156" y="26" rx="0" ry="0" width="50" height="6" />
        <circle cx="33" cy="69" r="17" />
        <rect x="60" y="65" rx="0" ry="0" width="45" height="6" />
        <rect x="304" y="65" rx="0" ry="0" width="52" height="6" />
        <rect x="16" y="114" rx="0" ry="0" width="340" height="15" />
        <rect x="263" y="208" rx="0" ry="0" width="94" height="19" />
        <rect x="16" y="141" rx="0" ry="0" width="340" height="15" />
        <rect x="16" y="166" rx="0" ry="0" width="340" height="15" />
      </ContentLoader>
    )
  }

  // 操作
  return (
    <div className={styles.root}>
      <div className="root-wrapper">
        <NavBar
          onBack={() => history.go(-1)}
          right={
            <span>
              <Icon type="icongengduo" />
            </span>
          }>
          {/* <pre id="codes">
            alert(1)
            <code id="codes2">console.log(1)</code>
          </pre> */}
          {detail && (
            <div className="nav-author">
              <img src={detail.aut_photo} alt="" />
              <span className="name">{detail.aut_name}</span>
              <span
                className={classNames(
                  'follow',
                  detail.is_followed ? 'followed' : ''
                )}>
                {detail.is_followed ? '已关注' : '关注'}
              </span>
            </div>
          )}
        </NavBar>
        {/* 危险XSS */}
        {/* <div
          dangerouslySetInnerHTML={{
            __html: `<div onclick="document.body.innerHTML = ''">1111</div>`,
          }}></div> */}
        {/* 文章详情和评论 */}
        {renderArticle()}

        {/* 底部评论栏 */}
        <CommentFooter
          comments={detail!.comm_count}
          onShowComment={onShowComment}
          onCommentPopup={onCommentShow}
          onCollected={() =>
            onArticle('is_collected', detail!.art_id, fav, unFav)
          }
          onLike={() => onArticle('attitude', detail!.art_id, like, unLike)}
          attitude={detail?.attitude}
          is_collected={detail?.is_collected}
        />
        {/* 对文章评论-弹层 */}
        <Popup
          destroyOnClose
          className="comment-popup"
          position="bottom"
          visible={commentVisible}
          onMaskClick={onCommentHide}
          bodyStyle={{
            height: '40vh',
          }}>
          {/* <div className="comment-popup-wrapper"> */}
          <CommentInput onClose={onCommentHide} onAddComment={onAddComment} />
          {/* </div> */}
        </Popup>
        {/* 对评论-回复弹层 */}
        <Popup
          destroyOnClose
          className="reply-popup"
          position="right"
          visible={commentReply.visible}>
          {/* <div className="comment-popup-wrapper"> */}
          <Reply
            onClose={onCommentReplyHide}
            commentItem={commentReply.commentItem}
          />
          {/* </div> */}
        </Popup>
      </div>
    </div>
  )
}

export default Article
